package logger

import (
	"bytes"
	"fmt"
	"os"
	"sync"
	"sync/atomic"
)

// StreamMessageHandler
type StreamMessageHandler struct {
	LogDir         string
	LogFileName    string
	LogExt         string
	LogFilePath    string
	LogBuffer      *bytes.Buffer
	BufferLine     uint64
	LogFileHandler *os.File
	mutex          sync.Mutex
}

var logLineOps uint64 = 0

//  Write write log to buffer
func (handler *StreamMessageHandler) Write(message []byte) {
	handler.mutex.Lock()
	handler.LogBuffer.Write(message)
	handler.mutex.Unlock()

	atomic.AddUint64(&logLineOps, 1)
	// if log buffer line Greater than maximum number of rows, it will sync log
	if atomic.LoadUint64(&logLineOps) >= maxLogSyncLine {
		handler.SyncLog()
	}
}

// SyncLog interval sync log stream buffer
func (handler *StreamMessageHandler) SyncLog() {
	handler.mutex.Lock()
	defer handler.mutex.Unlock()
	if handler.LogBuffer.Len() > 0 {
		logLineOps = 0
		message := handler.LogBuffer.Bytes()
		handler.LogBuffer.Reset()
		handler.LogFileHandler.Write(message)
	}
}

func openLogFile(logfile string) (logFile *os.File) {
	if logfile == "" {
		logFile = os.Stdout
		return
	}
	logFile, err := os.OpenFile(logfile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		panic(fmt.Sprintf("log file create error: %v", err))
	}

	return
}
